{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plots for Near-Optimal Analysis\n",
    "***"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pypsa\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import geopandas as gpd\n",
    "import matplotlib.pyplot as plt\n",
    "from vresutils.snakemake import MockSnakemake, Dict\n",
    "from itertools import product"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from plotting import collection as clt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.style.use('bmh')\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Preliminaries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "d = \"../graphics/\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "snakemake = MockSnakemake(\n",
    "    input=Dict(\n",
    "        investments=\"results/summaries/investments.csv\",\n",
    "        energy=\"results/summaries/energy.csv\",\n",
    "        storage_capacity=\"results/summaries/storage_capacity.csv\",\n",
    "        generation_capacity=\"results/summaries/generation_capacity.csv\",\n",
    "        line_capacity=\"results/summaries/line_capacity.csv\",\n",
    "        link_capacity=\"results/summaries/link_capacity.csv\",\n",
    "        line_volume=\"results/summaries/line_volume.csv\",\n",
    "        link_volume=\"results/summaries/link_volume.csv\",\n",
    "        line_energy_balance=\"results/summaries/line_energy_balance.csv\",\n",
    "        link_energy_balance=\"results/summaries/link_energy_balance.csv\",\n",
    "        ginis=\"results/summaries/gini.csv\",\n",
    "        network=\"results/networks/elec_s_100_ec_lcopt_2H.nc\",\n",
    "        network_tmin1=\"results/networks/elec_s_100_ec_lcopt_2H_tol0.01_cat-totals_obj-Transmission++min.nc\",\n",
    "        network_tmin5=\"results/networks/elec_s_100_ec_lcopt_2H_tol0.05_cat-totals_obj-Transmission++min.nc\",\n",
    "        network_tmin10=\"results/networks/elec_s_100_ec_lcopt_2H_tol0.1_cat-totals_obj-Transmission++min.nc\",\n",
    "        shapes=\"pypsa-eur/resources/regions_onshore_elec_s_100.geojson\"\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Read Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "header = [i for i in range(7)]\n",
    "investments = pd.read_csv(snakemake.input.investments, index_col=0, header=header)\n",
    "energy=pd.read_csv(snakemake.input.energy, index_col=[0,1], header=header)\n",
    "storage_capacity=pd.read_csv(snakemake.input.storage_capacity, index_col=[0,1], header=header)\n",
    "generation_capacity=pd.read_csv(snakemake.input.generation_capacity, index_col=[0,1], header=header)\n",
    "line_capacity=pd.read_csv(snakemake.input.line_capacity, index_col=0, header=header)\n",
    "link_capacity=pd.read_csv(snakemake.input.link_capacity, index_col=0, header=header)\n",
    "line_volume=pd.read_csv(snakemake.input.line_volume, index_col=0, header=header)\n",
    "link_volume=pd.read_csv(snakemake.input.link_volume, index_col=0, header=header)\n",
    "line_energy_balance=pd.read_csv(snakemake.input.line_energy_balance, index_col=0, header=header)\n",
    "link_energy_balance=pd.read_csv(snakemake.input.link_energy_balance, index_col=0, header=header);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def adjust_column_names(df):\n",
    "    new_column_names = []\n",
    "    for col in df.columns.tolist():\n",
    "        col = list(col)  # tuple does not allow item assignment\n",
    "        if col[-2] == \"all\":\n",
    "            col[-2] = \"-\".join([col[-2], col[-3]])\n",
    "        new_column_names.append(tuple(col))\n",
    "\n",
    "    df.columns = pd.MultiIndex.from_tuples(new_column_names, names=df.columns.names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for df in [\n",
    "    investments,\n",
    "    line_volume,\n",
    "    link_volume,\n",
    "    generation_capacity,\n",
    "    storage_capacity,\n",
    "    energy,\n",
    "]:\n",
    "    adjust_column_names(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def read_gini(gini_fn, ln_vol, lk_vol):\n",
    "    tvol = (ln_vol.sum()/1e3 + lk_vol.sum()/1e3).reset_index()\n",
    "    gini = pd.read_csv(gini_fn, index_col=0, header=header).T.reset_index()\n",
    "    gini = pd.concat([gini,tvol[0]], axis=1)\n",
    "    gini = gini.rename(columns={0: 'tvol'})\n",
    "    return gini.loc[gini.variable_name=='all']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gini = read_gini(snakemake.input.ginis, line_volume, link_volume)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = pypsa.Network(snakemake.input.network)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n_tmin1 = pypsa.Network(snakemake.input.network_tmin1)\n",
    "n_tmin5 = pypsa.Network(snakemake.input.network_tmin5)\n",
    "n_tmin10 = pypsa.Network(snakemake.input.network_tmin10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_network(n, fn=f\"{d}map-opt.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_network(n_tmin1, fn=f\"{d}map-tmin1.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_network(n_tmin5, fn=f\"{d}map-tmin5.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_network(n_tmin10, fn=f\"{d}map-tmin10.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "shapes = gpd.read_file(snakemake.input.shapes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Execute Plotting Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_gini(gini, n, annot={}, fn=f\"{d}gini.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lorentz_networks = {\"Optimum\": n, \"Min TVOL 1%\": n_tmin1, \"Min TVOL 5%\": n_tmin5, \"Min TVOL 10%\": n_tmin10}\n",
    "clt.plot_lorentz(lorentz_networks, fn=f\"{d}lorentz.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for c in [\"solar\", \"offwind-ac\", \"offwind-dc\", \"onwind\"]:\n",
    "    clt.plot_curated_boxplots(generation_capacity, carrier=c, fn=f\"{d}boxplots-{c}.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for c in [\"H2\", \"battery\"]:\n",
    "    clt.plot_curated_boxplots(storage_capacity, carrier=c, fn=f\"{d}boxplots-{c}.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_capacity_correlation(generation_capacity, storage_capacity, line_volume, link_volume, fn=f\"{d}capacity-correlation.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_energy_correlation(energy, fn=f\"{d}energy-correlation.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_violins(generation_capacity, storage_capacity, fn=f\"{d}violins.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_energy_pie(n, fn=f\"{d}energy-pie.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_cost_bar(n, order=True, relative=False, fn=f\"{d}cost-bar-abs.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_cost_bar(n, order=True, relative=True, fn=f\"{d}cost-bar-rel.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_dominance(n, n_tmin1, n_tmin5, n_tmin10, shapes=shapes, attr='energy', fn=f\"{d}dominance-energy.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_dominance(n, n_tmin1, n_tmin5, n_tmin10, shapes=shapes, attr='p_nom_opt', fn=f\"{d}dominance-capacity.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_bar_collection(generation_capacity, storage_capacity, fn=f\"{d}capacity-bars.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_space(n, investments, line_volume, link_volume, fn=f\"{d}space.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_space_presentation(n, investments, line_volume, link_volume, fn=f\"{d}space-pres.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "groups = [\"wind\", \"onwind\", \"offwind\", \"solar\", \"all-StorageUnit\", \"all-Transmission\", \"battery\", \"H2\"]\n",
    "senses = [\"min\", \"max\"]\n",
    "args = [n, investments, line_volume, link_volume]\n",
    "for oc, ocs in product(groups, senses):\n",
    "    kwargs = {\n",
    "        \"other_carrier\": oc,\n",
    "        \"other_carrier_sense\": ocs\n",
    "    }\n",
    "    clt.plot_space_presentation(*args, **kwargs, fn=f\"{d}space-pres-{oc}-{ocs}.pdf\")\n",
    "    clt.plot_space(*args, **kwargs, fn=f\"{d}space-{oc}-{ocs}.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clt.plot_capacity_bar(n, fn=f\"{d}capacity-bar.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for tol in [0.005,0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.1]:\n",
    "    fn = f\"../results/networks/elec_s_100_ec_lcopt_2H_tol{tol}_cat-totals_obj-transmission++min.nc\"\n",
    "    n_tol = pypsa.Network(fn)\n",
    "    clt.plot_network(n_tol, fn=fig_folder+f\"map-tmin-{tol}.pdf\")\n",
    "    del n_tol"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Some Misc Checks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "(n.lines.s_nom_opt * n.lines.length / 1e6).sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "(n.links.p_nom_opt * n.links.length / 1e6).sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.storage_units.groupby('carrier').sum().p_nom_opt / 1e3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.generators.groupby('carrier').sum().p_nom_opt / 1e3 # GW"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.generators['energy'] = n.generators_t.p.multiply(n.snapshot_weightings, axis=0).sum()\n",
    "n.generators.groupby('carrier').sum().energy / 1e6 # TWh"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "c = aggregate_costs(n)\n",
    "c = c.groupby(level=2).sum() / 1e9 # bn Euro\n",
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "load = n.loads_t.p_set.multiply(n.snapshot_weightings, axis=0).sum().sum() / 1e6 #TWh\n",
    "load"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "c.sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "c.sum() / load * 1e3 # EUR/MWh"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "net.global_constraints.mu"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "get_system_transmission_volume(n, '_opt')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.generators.groupby(\"carrier\").sum().p_nom_max / 1e3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
